#！/bin/sh

# 使用方法 build.sh 应用名称 操作系统 系统架构(amd64)

if [[ ! $1 ]]; then
  echo "请输入应用名(server|client)"
  exit
fi
app=$1
# 获取应用版本，git版本信息
verinfo=$(git rev-parse --short HEAD)
echo "应用版本: ${verinfo}"
# 获取操作系统
if [ -n "$2" ]; then
  os=$2
else
  os=$(uname -s | awk '{print tolower($0)}')
fi
# 获取系统架构
if [ -n "$3" ]; then
  arch=$3
else
  arch=amd64
fi
# 构建时间
appVerTag="-X 'bjmes/src/appTool.Version=${verinfo}'"
timeTag="-X 'bjmes/src/appTool.BuildTime=$(date '+%Y-%m-%d %H:%M:%S')'"
branchFlag="-X 'bjmes/src/appTool.GitBranch=$(git name-rev --name-only HEAD)'"
commitFlag="-X 'bjmes/src/appTool.CommitId=${verinfo}'"
# 获取go版本
goVersion=$(go version | awk '{print $3}')
goVersionFlag="-X 'bjmes/src/appTool.GoVersion=${goVersion}'"
staticTag="-extldflags '-static'" #关闭符号链接
ldflags="-s -w ${staticTag} ${timeTag} ${goVersionFlag} ${branchFlag} ${commitFlag} ${appVerTag} "
cd "./$app"
if [ $? -ne 0 ]; then
  echo "编译目录切换失败"
  exit
fi
srcDir=$(pwd)
echo "编译参数: CGO_ENABLED=0 GOOS=${os} GOARCH=${arch}  go build -ldflags \"${ldflags}\" $srcDir"
echo "开始编译"
CGO_ENABLED=0 GOOS=${os} GOARCH=${arch}  go build -ldflags "${ldflags}" "$srcDir"
echo "编译结束"